/*
 * BanBu_HisFriendViewController
 * @description 本文件提供个人空间关注和粉丝界面的ViewController
 * @package
 * @author 		***
 * @copyright
 * @version 		1.0
 * @description 本文件提供个人空间关注和粉丝界面的ViewController
 */

#import "BanBu_HisFriendViewController.h"
#import "AppDataManager.h"
#import "AppCommunicationManager.h"
#import "BanBuRequestDelegate.h"
#import "BanBu_HisFriendCell.h"
#import "BanBu_NavButton.h"
#import "BanBu_PersonDataViewController.h"
#import "BanBu_ThemeManager.h"
#import "BanBu_ImageView.h"
@interface BanBu_HisFriendViewController ()

@end

@implementation BanBu_HisFriendViewController
@synthesize hisFriends,linkRow;
-(void)viewWillAppear:(BOOL)animated
{
    [UIView setAnimationsEnabled:YES];
    [super viewWillAppear:animated];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}
-(void)dealloc
{
    [super dealloc];
    [AppComManager cancalHandlesForObject:self];
    [hisFriends release],hisFriends = nil;
    [cacheArray release],cacheArray = nil;
    [moreView release],moreView = nil;
}
-(void)viewDidAppear:(BOOL)animated
{
    self.tableView.tableFooterView = moreView;
    [super viewDidAppear:animated];
}
-(void)viewWillDisappear:(BOOL)animated
{
    [AppComManager cancalHandlesForObject:self];
    [super viewWillDisappear:animated];
}
-(void)popself
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    if([_relationShip isEqualToString:@"g"])
    {
        self.title = NSLocalizedString(@"peopleAttention", nil);
    }
    if([_relationShip isEqualToString:@"f"])
    {
        self.title = NSLocalizedString(@"peopleFans", nil);
    }
    
//    BanBu_NavButton *btn_return = [[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeBack];
//    btn_return.frame=CGRectMake(0, 0,50, 30);
//    [btn_return addTarget:self action:@selector(popself) forControlEvents:UIControlEventTouchUpInside];
//    //    [btn_return setTitleEdgeInsets:UIEdgeInsetsMake(3, 2, 2, 2)];
//    [btn_return setTitle:NSLocalizedString(@"returnButton", nil) forState:UIControlStateNormal];
//    btn_return.titleLabel.font = [UIFont systemFontOfSize:14];
//    UIBarButtonItem *cancelItem = [[[UIBarButtonItem alloc] initWithCustomView:btn_return] autorelease];
//    self.navigationItem.leftBarButtonItem = cancelItem;
//    [btn_return release];

        //初始化数据
    currentPage = 0;
    
    alreadyRefresh = YES;
    isLoading      = NO;
    moreView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
    lab = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, 320,20)];
    lab.font= [UIFont systemFontOfSize:15];
    lab.backgroundColor =[UIColor colorWithRed:254.0/255.0 green:250.0/255.0 blue:239.0/255.0 alpha:1];
    lab.textAlignment = kTextAlignmentCenter;
    lab.textColor = [UIColor grayColor];
    lab.backgroundColor = [UIColor clearColor];
    moreView.backgroundColor = [UIColor clearColor];
    [moreView addSubview:lab];
    loadingView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    loadingView.hidden = NO;
    [loadingView setHidesWhenStopped:YES];
    loadingView.frame = CGRectMake(0, 0, 50, 50);
    loadingView.center = CGPointMake(160-([NSLocalizedString(@"loadingNotice", nil) sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:CGSizeMake(320, 20) lineBreakMode:kTextLineBreakByWordWrapping].width/2)-15, 20);
    
    [moreView addSubview:loadingView];
    [loadingView release];
    
    
    
    
    hisFriends = [[NSMutableArray alloc] init];
    cacheArray = [[NSMutableArray alloc]initWithCapacity:20];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, __MainScreen_Width, __MainScreen_Height-44) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate   = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
    
    self.tableView.backgroundView = [[[BanBu_ImageView alloc] initWithBackGroundImageType:UIImageViewCreatTypeTable] autorelease];
    [_tableView release];
    
    
    
    
    //加载首页数据
    [self loadingData];
    [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"loadingNotice", nil) activityAnimated:YES];
}


-(void)loadingData
{
    if(currentPage == 1)
    {
        currentPage = 3;
    }
    else
    {
        currentPage ++;
    }
    NSMutableDictionary *resDic = [NSMutableDictionary dictionary];
    [resDic setValue:_relationShip forKey:@"linkkind"];
    [resDic setValue:[NSString stringWithFormat:@"%d",currentPage] forKey:@"pageno"];
    [resDic setValue:[MyAppDataManager getLanguageSubmitToServer] forKey:@"lang"];
    [resDic setValue:_userid forKey:@"userid"];
    [AppComManager getBanBuData:BanBu_Get_Friendlist_Byuid par:resDic delegate:self];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}
#pragma mark -
#pragma mark tableviewDataSource

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 64;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return hisFriends.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIndentifier = @"hisFriendCellIndentifier";
    BanBu_HisFriendCell *cell = (BanBu_HisFriendCell *)[tableView dequeueReusableCellWithIdentifier:cellIndentifier];
    if(!cell)
    {
        cell = [[[BanBu_HisFriendCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier] autorelease];
//        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    if(hisFriends.count){
        if([[hisFriends valueForKey:keyPersonalInfo] count])
        {
            NSDictionary *buddy = [hisFriends objectAtIndex:indexPath.row];
            [cell updateHisFriendCell:buddy];
            if([[buddy valueForKey:@"linked"] boolValue]) //是否关注
            {
                [cell.linkBtn setBackgroundImage:[ThemeManager getThemeImage:@"app_button_welcomelogin.png"] forState:UIControlStateNormal];
                [cell.linkBtn setBackgroundImage:[ThemeManager getThemeImage:@"app_button_welcomelogin.png"] forState:UIControlStateHighlighted];
                [cell.linkBtn setTitle:@"+" forState:UIControlStateNormal];
            }
            else
            {
                [cell.linkBtn setBackgroundImage:[ThemeManager getThemeImage:@"app_btn_blue.png"] forState:UIControlStateNormal];
                cell.linkBtn.userInteractionEnabled = YES;
                [cell.linkBtn setTitle:@"+" forState:UIControlStateNormal];
                cell.linkBtn.tag = indexPath.row+222;
                [cell.linkBtn addTarget:self action:@selector(addLink:) forControlEvents:UIControlEventTouchUpInside];
                
            }
            
        }}
    return cell;
    
    
}
#pragma mark -
#pragma mark tableviewDelegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.linkRow = indexPath.row;
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *buddy = [hisFriends objectAtIndex:indexPath.row];

    
    if([[[buddy valueForKey:keyPersonalInfo] valueForKey:@"pname"]length])
    {
        BanBu_PersonDataViewController *peopleFfofile = [[BanBu_PersonDataViewController alloc] initWithProfile:[buddy valueForKey:keyPersonalInfo]];
        [self.navigationController pushViewController:peopleFfofile animated:YES];
        [peopleFfofile release];
    }

}
#pragma mark -
#pragma mark banbuRequestDidFinish
- (void)banbuRequestDidFinished:(NSDictionary *)resDic error:(NSError *)error
{
    [TKLoadingView dismissTkFromView:self.view animated:NO afterShow:0];
    if(error)
    {
        if([error.domain isEqualToString:BanBuDataformatError])
        {
            [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"network_error", nil) activityAnimated:NO duration:2.0];
            [loadingView stopAnimating];
            lab.text = NSLocalizedString(@"network_error", nil);
        }
        else
        {
            [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"network_error", nil) activityAnimated:NO duration:2.0];
            [loadingView stopAnimating];
            lab.text = NSLocalizedString(@"network_error", nil);
            
        }
        [loadingView stopAnimating];
        if(currentPage>3)
        {
            currentPage--;
        }
        else
        {
            currentPage =1;
        }
        isLoading      = NO;
        return;

    }
    else
    {
        if([AppComManager respondsDic:resDic isFunctionData:BanBu_Get_Friendlist_Byuid])
        {
        if([[resDic valueForKey:@"ok"] isEqual:@"y"])
        {
            NSString *flistString = [[[UserDefaults valueForKey:MyAppDataManager.useruid] valueForKey:@"friendlist"] valueForKey:@"x"];
            flistString = [NSString stringWithFormat:@",%@,",flistString];
            NSString *friendString = [[[UserDefaults valueForKey:MyAppDataManager.useruid] valueForKey:@"friendlist"] valueForKey:@"h"];
            friendString = [NSString stringWithFormat:@",%@,",friendString];
            NSString *guanzhuString = [[[UserDefaults valueForKey:MyAppDataManager.useruid] valueForKey:@"friendlist"] valueForKey:@"g"];
            guanzhuString = [NSString stringWithFormat:@",%@,",guanzhuString];
            NSMutableArray *list = [NSMutableArray arrayWithArray:[resDic valueForKey:@"list"]];
            for(int i = 0;i<[[resDic valueForKey:@"list"] count];i++)
            {
                NSMutableDictionary *aDic = [NSMutableDictionary dictionaryWithDictionary:[[resDic valueForKey:@"list"] objectAtIndex:i]];
                NSMutableDictionary *userInfor = [[NSMutableDictionary alloc] initWithDictionary:[aDic valueForKey:@"userinfor"]];
                
                if([MyAppDataManager theRevisedName:[[aDic valueForKey:@"userinfor"] valueForKey:@"pname"] andUID:[aDic valueForKey:@"userid"]])
                {
                    
                    [userInfor setValue:[MyAppDataManager theRevisedName:[userInfor valueForKey:@"pname"] andUID:[aDic valueForKey:@"userid"]] forKey:@"pname"];
                    [aDic setValue:userInfor forKey:@"userinfor"];
                    
                }
                if([friendString rangeOfString:[NSString stringWithFormat:@",%@,",[aDic valueForKey:@"userid"]]].location != NSNotFound||[guanzhuString rangeOfString:[NSString stringWithFormat:@",%@,",[aDic valueForKey:@"userid"]]].location != NSNotFound||[[aDic valueForKey:@"userid"] isEqual:MyAppDataManager.useruid])
                {
                    [aDic setValue:[NSNumber numberWithBool:YES] forKey:@"linked"];//已关注
                }
                else
                {
                    [aDic setValue:[NSNumber numberWithBool:NO] forKey:@"linked"];//未关注
                }
                BOOL isBlack = NO;
                if([flistString rangeOfString:[NSString stringWithFormat:@",%@,",[aDic valueForKey:@"userid"]]].location != NSNotFound&&flistString.length)
                {
                    isBlack = YES;
                }
                if(currentPage == 1)
                {
//                    [hisFriends removeAllObjects];
//                    [cacheArray removeAllObjects];
                    if(!isBlack)
                    {
                        if(i<20)
                        {
                            [hisFriends addObject:aDic];
                        }
                        else
                        {
                            [cacheArray addObject:aDic];
                        }
                    }
                }
                
                else
                {
                       [list replaceObjectAtIndex:i withObject:aDic];
                }
            }
            if(currentPage == 1&&hisFriends.count)
            {
                self.tableView.tableFooterView = moreView;
                [self.tableView reloadData];
                [self.tableView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:self.tableView];
            }
            else
            {
                [cacheArray addObjectsFromArray:list];
                if(!alreadyRefresh&&isLoading&&cacheArray.count)
                {
                    [self startLoadNextPage];
                }
                if(!cacheArray.count)
                {
                    [loadingView stopAnimating];
                    if(currentPage>3)
                    {
                        currentPage--;
                    }
                    else
                    {
                        currentPage =1;
                    }
                    [loadingView stopAnimating];
                    lab.text = NSLocalizedString(@"noData", nil);
                }
            }
        }
        else
        {
            [loadingView stopAnimating];
            if(currentPage>3)
            {
                currentPage--;
            }
            else
            {
                currentPage =1;
            }
            [loadingView stopAnimating];
            lab.text = NSLocalizedString(@"noData", nil);
//            [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"network_error", nil) activityAnimated:NO duration:2.0];
            
        }
        }
        else if([AppComManager respondsDic:resDic isFunctionData:BanBu_Set_Friend_Link])
        {
            self.view.userInteractionEnabled = YES;
            if([[resDic valueForKey:@"ok"]boolValue])
            {
                NSMutableDictionary *uidDic = [NSMutableDictionary dictionaryWithDictionary:[UserDefaults valueForKey:MyAppDataManager.useruid]];
                [uidDic setValue:[resDic valueForKey:@"friendlist"] forKey:FriendShip];
                
                [UserDefaults setValue:uidDic forKey:MyAppDataManager.useruid];
                [UserDefaults synchronize];
                
                NSMutableDictionary *aDic = [NSMutableDictionary dictionaryWithDictionary:[hisFriends objectAtIndex:linkRow]];
                [aDic setValue:[NSNumber numberWithBool:YES] forKey:@"linked"];//是否关注
                [hisFriends replaceObjectAtIndex:linkRow withObject:aDic];
                [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:linkRow inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
                
                
                BanBu_HisFriendCell *cell = (BanBu_HisFriendCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:linkRow inSection:0]];
                [cell.linkBtn removeTarget:self action:@selector(addLink:) forControlEvents:UIControlEventTouchUpInside];
                [TKLoadingView dismissTkFromView:self.navigationController.view animated:NO afterShow:0];
                [TKLoadingView showTkloadingAddedTo:self.navigationController.view point:CGPointMake(0, 190) title:NSLocalizedString(@"linkSuccess", nil) activityAnimated:NO duration:1.0];

            }
            else
            {
                [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:[MyAppDataManager IsInternationalLanguage:[resDic valueForKey:@"error"]] activityAnimated:NO duration:1.0];
            }
        }
    }
    isLoading = NO;
}

-(void)startLoadNextPage
{
    if(cacheArray.count)
    {
//        NSLog(@"%d",cacheArray.count);
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[hisFriends count] inSection:0];
        [hisFriends addObjectsFromArray:cacheArray];
        [cacheArray removeAllObjects];
            [UIView animateWithDuration:0.5 animations:^{
            [self.tableView reloadData];
            [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        }];
        alreadyRefresh = YES;
    }
    if(!cacheArray.count)
    {
        [self loadingData];
        isLoading = YES;
    }
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if([keyPath isEqual:@"contentOffset"])
    {
        if(![lab.text isEqual:NSLocalizedString(@"loadingMore", nil)]&&self.tableView.contentOffset.y>self.tableView.contentSize.height-__MainScreen_Height+44+30)
        {
            if(!isLoading)
            {
                alreadyRefresh = NO;
                [loadingView startAnimating];
                lab.text = NSLocalizedString(@"loadingNotice", nil);
                [self performSelector:@selector(startLoadNextPage) withObject:nil afterDelay:0.5];
                isLoading = YES;
            }
            else
            {
                alreadyRefresh = NO;
            }
        }
    }
}
-(void)addLink:(UIButton *)sender
{
    [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"chuliNotice", nil) activityAnimated:YES];
    NSInteger row = sender.tag-222;
    linkRow = row;
    NSString *action = @"link";
    NSMutableDictionary *pars = [NSMutableDictionary dictionaryWithCapacity:2];
    [pars setValue:[[hisFriends objectAtIndex:row] valueForKey:@"userid"] forKey:LinkTouID];
    [pars setValue:action forKey:Action];
    [AppComManager getBanBuData:BanBu_Set_Friend_Link par:pars delegate:self];
    self.view.userInteractionEnabled = NO;
}

@end
